<?php
namespace app\controllers;
use app\models\AccessLogModel;
use app\models\ApplyModel;

class IndexController extends AdminController {
    public function index()
    {
        $beginLastweek  = date('Y-m-d', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')));
        $endLastweek    = date('Y-m-d',mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y')));
        $p_beginLastweek  = date('Y-m-d', mktime(0,0,0,date('m'),date('d')-date('w')+1-14,date('Y')));
        $p_endLastweek    = date('Y-m-d',mktime(23,59,59,date('m'),date('d')-date('w')+7-14,date('Y')));
        //上星期申请统计
        $applyModel = new ApplyModel();
        $nextApply      = $applyModel->get('select count(*) as total from '.$applyModel->getTable()." where created_at between '{$beginLastweek}' and '{$endLastweek}' ");
        $nextNextApply  = $applyModel->get('select count(*) as total from '.$applyModel->getTable()." where created_at between '{$p_beginLastweek}' and '{$p_endLastweek}' ");

        //上星期浏览统计
        $logModel = new AccessLogModel();
        $nextLog     = $logModel->get('select count(*) as total from '.$logModel->getTable()." where created_at between '{$beginLastweek}' and '{$endLastweek}' ");
        $nextNextLog  = $logModel->get('select count(*) as total from '.$logModel->getTable()." where created_at between '{$p_beginLastweek}' and '{$p_endLastweek}' ");

        //未处理的申请
        $notRead = $applyModel->get('select count(*) as total from '.$applyModel->getTable()." where is_read = '0' ");

        $this->assign('nextApply', $nextApply['total']);
        $this->assign('nextNextAply', $nextNextApply['total']);
        $this->assign('nextLog', $nextLog['total']);
        $this->assign('nextNextLog', $nextNextLog['total']);
        $this->assign('notRead', $notRead['total']);

        $this->display();
    }

    //最近六个月统计
    public function getSixCount()
    {
        $logModel = new AccessLogModel();
        $data = array();
        $month = $this->getlastMonthDays(date('Y-m-01'));
        for($i = 0; $i <6; $i ++)
        {
            $sixMonthLog = $logModel->get('select count(*) as total from '.$logModel->getTable()." where created_at between '{$month[0]}' and '{$month[1]}' ");
            $data[] = array(
                $month[1],
                $sixMonthLog['total']
            );
            $month = $this->getlastMonthDays(date('Y-m-d',strtotime($month[0]." -2 day")));
        }

        return $this->request->json(array_reverse($data));
    }

    public function getlastMonthDays($date){
        $timestamp=strtotime($date);
        $firstday = date("Y-m-01",strtotime($date));
        $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
        return array($firstday,$lastday);
  }
}